package ui;

import dao.SAMDao;
import entity.UserInfoEntity;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginFrame extends JFrame {
    private JTextField textFieldUsername;
    private JPasswordField passwordField;

    public LoginFrame() {
        setTitle("房屋租赁管理");
        setSize(1000, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        JLabel labelUsername = new JLabel("用户名:");
        textFieldUsername = new JTextField(20);
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(labelUsername, gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        panel.add(textFieldUsername, gbc);

        JLabel labelPassword = new JLabel("密码:");
        passwordField = new JPasswordField(20);
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(labelPassword, gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        panel.add(passwordField, gbc);

        JButton buttonLogin = new JButton("登录");
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        buttonLogin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    login();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        panel.add(buttonLogin, gbc);

        add(panel);
    }

    public void login() throws Exception {
        String username = textFieldUsername.getText();
        String password = new String(passwordField.getPassword());
        SAMDao dao = new SAMDao();
        UserInfoEntity userInfoEntity = dao.fetchData(username, password);
        if (userInfoEntity!=null){
            HouseInfoManagementGUI house = new HouseInfoManagementGUI();
            house.showa();
            dispose(); // 关闭当前登录窗口
        }else {
            JOptionPane.showMessageDialog(null, "用户名或密码错误", "登录失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        LoginFrame loginFrame = new LoginFrame();
        loginFrame.setVisible(true);
    }
}
